﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;

namespace Cemit.PolyServer.Main
{
    [System.Obsolete("使用PolyServerApplication启动服务器")]
    class Program
    {
        [Obsolete("直接new服务器对象")]
        const string SERVER_LIST_FILE_NAME = "ServerTypeList";

        static void Main(string[] args)
        {
            new MainServer()
                .StartWithConfig();
        }

        [Obsolete("直接new服务器对象")]
        void StartServerFromConfig()
        {
            List<Type> servers = GetAllServers();

            LogAllServers();

            int launchIndex = ReadServerIndex();

            object netServer = servers[launchIndex].Assembly.CreateInstance(servers[launchIndex].FullName);

            if (netServer == null)
            {
                throw new Exception($"服务器类型错误或没有默认构造函数：{servers[launchIndex]}");
            }
            if (!(netServer is PolyServer))
            {
                throw new Exception($"错误的服务器类型：{netServer.GetType()}");
            }

            string ip = Debug.Read(IsIp, "IP: ", "无效的地址!");
            int port = Debug.Read(IsPort, int.Parse, "Port: ", "端口范围为[1025, 65534]");

            Console.WriteLine($"开始启动服务器：{netServer.GetType().Name}  {ip}:{port}");

            ((PolyServer)netServer).Start(ip, port);

            bool IsIp(string p)
                => IPAddress.TryParse(p, out _);

            bool IsPort(string p)
                => int.TryParse(p, out int i) && i >= 1025 && i <= 65534;

            int ReadServerIndex()
            {
                int ret = -1;
                do
                {
                    Console.Write("启动服务器序号: ");
                    if (int.TryParse(Console.ReadLine(), out ret))
                    {
                        if (ret < 0 || ret >= servers.Count)
                        {
                            Console.WriteLine("错误的序号！");
                            ret = -1;
                        }
                    }
                    else
                    {
                        ret = -1;
                    }
                } while (ret == -1);
                return ret;
            }

            void LogAllServers()
            {
                Console.WriteLine("服务器列表：");

                int index = 0;
                foreach (var item in servers)
                {
                    Console.WriteLine($"{index++}: {item}");
                }
            }

            List<Type> GetAllServers()
            {
                List<Type> ret = new List<Type>();
                foreach (var item in GetServerListConfig().GetKeys())
                {
                    ret.Add(Type.GetType(GetServerListConfig().GetValue(item)));
                }
                return ret;
            }

            JsonConfigs GetServerListConfig()
                => Jsons.Get(SERVER_LIST_FILE_NAME);
        }
    }
}
